package com.dylovedz.javafxphone.service;

import com.dylovedz.javafxphone.controller.vo.WechatExcelVO;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;

import java.util.List;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.atomic.AtomicInteger;

public class MaterialTask extends RecursiveTask<List<WechatExcelVO>> {

    public static AtomicInteger donePage = new AtomicInteger(0);

    // 每个小任务最多执行10次
    private static final int MAX = 10;

    private int start;
    private int end;
    private WxMpServiceImpl wxMpService;
    private String outDir;
    private WechatService wechatService;

    public MaterialTask(WxMpServiceImpl wxMpService, WechatService wechatService, int start, int end, String outDir) {
        this.wxMpService = wxMpService;
        this.wechatService = wechatService;
        this.start = start;
        this.end = end;
        this.outDir = outDir;
    }

    @Override
    protected List<WechatExcelVO> compute() {

        if (end - start < MAX) {
            List<WechatExcelVO> liteRes = wechatService.getPageResult(wechatService, wxMpService, start, end, outDir, this);
            donePage.incrementAndGet();
            return liteRes;
        } else {
            System.out.println("任务分解");
            int middle = start + ((end - start) / 2);
            MaterialTask left = new MaterialTask(wxMpService, wechatService, start, middle, outDir);
            MaterialTask right = new MaterialTask(wxMpService, wechatService, middle + 1, end, outDir);
            // 并行执行两个小任务
            left.fork();
            right.fork();
            List<WechatExcelVO> leftList =  left.join();
            List<WechatExcelVO> rightList = right.join();
            leftList.addAll(rightList);
            return leftList;
        }
    }
}
